class myPromise {
  static PENDING = 'pending';
  static FULFILLED = 'fulfilled';
  static REJECTED = 'rejected'
  constructor(func) {
    this.status = myPromise.PENDING
    this.result = null
    this.resovleCallbacks = []
    this.rejectCallbacks = []
    try {
      func(this.resolve.bind(this), this.reject.bind(this))
    }
    catch (error) {
      this.reject(error)
    }
  }
  resolve (result) {
    setTimeout(() => {
      if (this.status === myPromise.PENDING) {
        this.status = myPromise.FULFILLED
        this.result = result
        this.resovleCallbacks.forEach(fn => fn(result))
      }
    })
  }
  reject (result) {
    setTimeout(() => {
      if (this.status === myPromise.PENDING) {
        this.status = myPromise.REJECTED
        this.result = result
        this.rejectCallbacks.forEach(fn => fn(result))
      }
    })
  }
  then (onFulfilled, onRejected) {
    return new myPromise((resolve, reject) => {
      // then里面传递的两个参数必须为函数
      onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : () => { }
      onRejected = typeof onRejected === 'function' ? onRejected : () => { }
      if (this.status === myPromise.PENDING) {
        this.resovleCallbacks.push(onFulfilled)
        this.rejectCallbacks.push(onRejected)
      }
      if (this.status === myPromise.FULFILLED) {
        setTimeout(() => {
          onFulfilled(this.result)
        })
      }
      if (this.status === myPromise.REJECTED) {
        setTimeout(() => {
          onRejected(this.result)
        })
      }
    })

  }
}

let p = new myPromise((resolve, reject) => {
  resolve('成功了')
  // reject('失败了')
  // throw new Error('失败了')
})
p.then(res => {
  console.log('第一次执行')
})
  .then(res => {
    console.log('第二次执行', res)
  })